import { OrderCount } from '@/api/order';
import { GetUserInfo } from '@/api/user';
import useCustomerService from '@/components/useCustomerService';
import useUserExamine from '@/hooks/useUserExamine';
import { DEFAULT_AVATAR } from '@/utils';
import { Tag } from '@antmjs/vantui';
import { Image, Text, View } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import classNames from 'classnames';
import dayjs from 'dayjs';
import { useMemo } from 'react';

import { useRequest, useVisible } from 'taro-hooks';
import { TemplateMessage } from 'types/user';

const VIP_ICON_MAP = {
  1: 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/vip-1.png',
  2: 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/vip-2.png',
  3: 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/vip-3.png',
  0: 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/vip-4.png',
};

const SERVICES_MENUS = [
  {
    label: '我的订单',
    icon: 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/my-icon-1.svg',
    path: `/pages/order/index`,
  },

  {
    label: '个性需求',
    icon: 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/my-icon-3.svg',
    path: '/pages/custom/index',
  },
  {
    label: '平台客服',
    icon: 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/my-icon-4.svg',
    key: 'kefu',
  },
];

const CHARA_MENUS = [
  {
    label: '邀请好友',
    icon: 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/my-icon-5.svg',
    path: '/pages/my/invite/index',
  },
  {
    label: '设置中心',
    icon: 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/my-icon-6.svg',
    path: '/pages/my/set/index',
  },
];

export default function Index() {
  const isVisible = useVisible();

  const { data: user } = useRequest(GetUserInfo, {
    refreshDeps: [isVisible],
    onSuccess: function (data) {
      if (!data?.name && data?.id)
        return Taro.reLaunch({ url: `/pages/info/index` });
    },
  });

  const { data: orderCount } = useRequest(OrderCount, {
    refreshDeps: [isVisible],
  });

  const allCount = useMemo(
    () =>
      Object.values(orderCount || {}).reduce(
        (accumulator, currentValue) => accumulator + currentValue,
        0
      ),
    [orderCount]
  );

  // ?是否到期
  const expire = useMemo(() => user?.vip === 0 && user.last_vip, [user]);

  // ?是否已登录
  const isLogin = useMemo(() => user?.id, [user]);

  const { renderNode: renderServiceNode, open: openService } =
    useCustomerService();

  const { isUserExamine } = useUserExamine();

  return (
    <>
      <View
        className='bg-black text-white text-[24px] bg-cover bg-center pt-8'
        style={{
          backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/my-bg.jpg)`,
        }}
      >
        {/* 已登录 */}
        {(isLogin && (
          <View className=' flex px-4 mb-4 relative'>
            <View className='w-[160px] h-[160px] relative mr-5'>
              <Image
                src={user?.headimg || DEFAULT_AVATAR}
                mode='aspectFill'
                className=' w-full h-full block  rounded-full bg-white border-solid border-[6px] border-white shadow-lg '
              />
            </View>

            <View className=' flex-1'>
              <View className=' text-xl font-bold text-black mt-[40px] flex items-center'>
                {user?.name}
                {/* Vip icon */}
                <View
                  className={classNames(
                    `h-[40px] bg-cover ml-2 ${
                      user?.vip === 1 || user?.vip === 2
                        ? 'w-[146px]'
                        : 'w-[166px]'
                    }`
                  )}
                  style={{
                    backgroundImage: `url(${
                      VIP_ICON_MAP[expire ? 3 : user?.vip || 0]
                    })`,
                  }}
                />

                {expire && (
                  <Text className=' text-[20px] text-gary4 ml-2'>
                    {user?.vip_end_time &&
                      dayjs(user.vip_end_time).format('YYYY-MM-DD')}
                    到期
                  </Text>
                )}
              </View>

              {user?.company && (
                <View className='py-1 leading-none px-3 mt-2 text-[#F2A922] text-xs bg-[rgba(255,255,255,.6)] rounded-full inline-block'>
                  <View
                    className='w-[24px] h-[24px] bg-cover inline-block mr-1 translate-y-[3px]'
                    style={{
                      backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-vip.svg)`,
                    }}
                  ></View>
                  {user?.company}
                </View>
              )}
            </View>
          </View>
        )) || (
          <View
            className=' flex px-4 mb-4'
            onClick={() => {
              Taro.navigateTo({
                url: `/pages/login/role`,
              });
            }}
          >
            <Image
              src={DEFAULT_AVATAR}
              mode='aspectFill'
              className=' w-[160px] h-[160px] rounded-full bg-white border-solid border-[6px] border-white shadow-lg mr-5'
            />
            <View className=' flex-1'>
              <Text className=' text-xl font-bold text-black block mt-[40px]'>
                登录/注册
              </Text>
              <Text className=' text-xs text-gary1 block'>
                点击登录，查看更多精彩信息
              </Text>
            </View>
          </View>
        )}

        {/* card */}
        <View className=' flex justify-between relative'>
          {/* un login mask */}
          {!isLogin && (
            <View
              className=' w-full h-full absolute left-0 top-0 z-20'
              onClick={() => {
                Taro.navigateTo({
                  url: '/pages/login/role',
                });
              }}
            ></View>
          )}

          {/* 帮豆 */}
          <View
            onClick={async () => {
              await isUserExamine();
              Taro.navigateTo({ url: '/pages/my/bangdou/index' });
            }}
            className=' w-[394px] h-[218px] bg-cover pt-[50px] pl-[40px] relative'
            style={{
              backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/my-card-1.png)`,
            }}
          >
            <View className=' block font-bold text-xl text-black'>
              帮豆 <Text className='ml-2 text-3xl'>{user?.beans || 0}</Text>
            </View>
          </View>

          {/* 积分 */}
          <View
            onClick={async () => {
              await isUserExamine();
              Taro.navigateTo({ url: '/pages/my/integral/index' });
            }}
            className=' w-[394px] h-[218px] bg-cover pt-[50px] pl-[40px] relative -ml-[24px]'
            style={{
              backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/my-card-2.png)`,
            }}
          >
            <View className=' block font-bold text-xl text-black'>
              积分 <Text className='ml-2 text-3xl'>{user?.points || 0}</Text>
            </View>
          </View>
        </View>

        {/* 我的服务 */}
        <View className='rounded-lg bg-white p-5 mx-[20px] relative'>
          {!isLogin && (
            <View
              className=' w-full h-full absolute left-0 top-0 z-20'
              onClick={() => {
                Taro.navigateTo({
                  url: '/pages/login/role',
                });
              }}
            ></View>
          )}

          <Text className=' block text-[#373948] text-lg mb-6'>我的服务</Text>
          <View className=' grid grid-cols-4 -mx-[20px] relative'>
            {SERVICES_MENUS.map((item) => (
              <View
                key={item.path}
                className='text-center'
                onClick={async () => {
                  await isUserExamine();
                  if (item?.key === 'kefu') return openService();

                  if (!item.path) return;
                  Taro.navigateTo({ url: item.path });
                }}
              >
                {item.label === '我的订单' && Boolean(allCount) && (
                  <Tag
                    round
                    type='danger'
                    className=' absolute left-[90px] -top-1 px-[12px] text-white'
                  >
                    {allCount}
                  </Tag>
                )}

                <Image
                  src={item.icon}
                  className='w-[44px] h-[44px] block mx-auto mb-2'
                />
                <Text className=' text-xs text-black'>{item.label}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* 特色服务 */}
        <View className='  mt-5 rounded-lg bg-white p-5 mx-[20px] relative'>
          {!isLogin && (
            <View
              className=' w-full h-full absolute left-0 top-0 z-20'
              onClick={async () => {
                Taro.navigateTo({
                  url: '/pages/login/role',
                });
              }}
            ></View>
          )}
          <Text className=' block text-[#373948] text-lg mb-6'>我的标签</Text>
          <View className=' grid grid-cols-4 -mx-[20px]'>
            {CHARA_MENUS.map((item) => (
              <View
                key={item.path}
                className='text-center'
                onClick={async () => {
                  //如果是设置， 则直接进入设置
                  if (item.path === '/pages/my/set/index') {
                    return Taro.navigateTo({
                      url: item.path,
                    });
                  }

                  //@ts-ignore
                  await Taro.requestSubscribeMessage({
                    tmplIds: [TemplateMessage.邀请结果提醒],
                  });
                  await isUserExamine();
                  if (!item.path) return;
                  Taro.navigateTo({
                    url: item.path,
                  });
                }}
              >
                <Image
                  src={item.icon}
                  className='w-[44px] h-[44px] block mx-auto mb-2'
                />
                <Text className=' text-xs text-black'>{item.label}</Text>
              </View>
            ))}
          </View>
        </View>
      </View>

      {renderServiceNode()}
    </>
  );
}
